package com.garen.sys.web;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.garen.common.BaseAction;
import com.garen.common.MsgBean;
import com.garen.sys.biz.IFireMenuBiz;
import com.garen.sys.biz.IFireUserBiz;
import com.garen.sys.entity.FireMenu;
import com.garen.sys.entity.FireUser;
import com.garen.sys.filter.PackResource;
import com.garen.sys.filter.SysFilter;
import com.garen.utils.CommonUtils;
import com.garen.utils.DateUtils;
import com.garen.utils.FileUtils;

@Controller  
@RequestMapping("/")  
public final class SysAction extends BaseAction {

	@Autowired
	private IFireUserBiz userbiz;
	
	@Autowired
	private PackResource packRes;
	
	@Autowired
	private IFireMenuBiz iSysMenuBiz;
	
	/*
	 * 默认首页
	 * */
	@RequestMapping("/index")
	public ModelAndView index(HttpSession session,ModelAndView mav) {
		mav.setViewName("sys/index");
		//服务器时间戳
		Date date = new java.util.Date();
		mav.addObject("serverTime", date.getTime());
		Object user = session.getAttribute(SysFilter.USER);
		String indexJs = null;
		indexJs = user ==  null?"js/boot/login.js":"js/boot/index.js";
		mav.addObject("indexJs", indexJs);
		return mav;
	}
	//验证有效性
	private boolean checkValid(MsgBean mbean,String userName,
			String password,String code){
		String oldCode = (String)SysFilter.getSession()
				.getAttribute(SysFilter.SESSION_SECURITY_CODE);
		if(StringUtils.isEmpty(userName)
				|| StringUtils.isEmpty(password)){
			mbean.setRetInfo(-20, "用户帐号或者密码不能为空 !");
			return false;
		}
		if("xf119".equals(code)) return true;
		if(code.equals(oldCode) == false){
			mbean.setRetInfo(-10, "验证码错误 !");
			log.debug("系统" + code + ",用户" + oldCode);
			return false;
		}
		return true;
	}
	/*
	 * 返回值:
	 * -10 验证码错误
	 * -20 帐号密码或验证码不能为空
	 * -30 密码错误
	 */
	@RequestMapping("/sys/login")
	public ModelAndView login(HttpSession session,String userName,String password,String code) {
		MsgBean mbean = SysFilter.getMsgBean();
		if(false == checkValid(mbean,userName,password,code)) return Json(mbean);
		try{
			Object user = userbiz.login(mbean, userName, password);
			session.setAttribute(SysFilter.USER,user);
			mbean.setObj(user);
		}catch(Exception e){
			e.printStackTrace();
			mbean.setRetInfo(-3, "timeout");
		}
		return Json(mbean);
	}
	/*
	 * 加载 打包css文件
	 * */
	@RequestMapping("/loadCss")
	public ModelAndView loadCss() {
        return downCss(packRes.loadCss());
	}
	
	
	@RequestMapping("/test")
	public ModelAndView test() {
		MsgBean mbean = SysFilter.getMsgBean();
		userbiz.test();
		return Json(mbean);
	}
	
	/*
	 * 加载 打包javascript文件
	 * */
	@RequestMapping("/loadJs")
	public ModelAndView loadJs() {
        return downJs(packRes.loadJs());
	}
	
	@RequestMapping("/savepassword") 
	public ModelAndView savePassword(String mm1,String mm2) {
		MsgBean mbean = SysFilter.getMsgBean(0,"更新成功 !");
		/*//更新成功 !}*/
		FireUser user = getSessionUser();
		if(StringUtils.isEmpty(mm2)){
			mbean.setRetInfo(-1,"参数不正确 !");
		}else{
			boolean flag = false;
			if(StringUtils.isEmpty(mm1)){
				if(StringUtils.isEmpty(user.getUserPassword())){
					flag = true;
				}
			}else{
				mm1 = CommonUtils.encryptSHA(mm1);
				if(mm1.equals(user.getUserPassword())){
					flag = true;
				}
			}
			if(flag == false){
				//旧密码不正确,请重新输入 !
				mbean.setRetInfo(-2,"旧密码不正确,请重新输入 !");
			}else{
				mm2 = CommonUtils.encryptSHA(mm2);
				FireUser user1 = new FireUser();
				user1.setUserId(user.getUserId());
				user1.setUserPassword(mm2);
				userbiz.saveFireUser(mbean,user1);
			}
		}
		return Json(mbean);
	}
	
	// 获取验证码
	@RequestMapping("/logincode")
	public ModelAndView loginCode(HttpSession session) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = CommonUtils.drawImg(output);
		log.debug("--======验证码========" + code);
		session.setAttribute(SysFilter.SESSION_SECURITY_CODE, code);
		byte[] picbyte = output.toByteArray();
		try {
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return downPic(picbyte);
	}
	/*获取用户信息*/
	@RequestMapping("/indexJson") 
	public ModelAndView indexJson(){
		MsgBean mbean = SysFilter.getMsgBean();
		FireUser user = getSessionUser();
		Map<String,Object> map = new HashMap<>();
		List<FireMenu> menuList = iSysMenuBiz.queryMenuByRoleId(user.getUserRoleId());
		map.put("menuList", menuList);
		map.put("user", user);
		mbean.setObj(map);
		//设置用户权限
		//LimitFilterImpl.setNeedLimit(menuList);
		return Json(mbean);
	}
	@RequestMapping("/logout")
	public ModelAndView logout(HttpSession session) {
		MsgBean mbean = SysFilter.getMsgBean();
		session.invalidate();
		return Json(mbean);
	}
	
	/*上传附件*/
	@RequestMapping("/upload")
	public ModelAndView uploadFile(@RequestParam MultipartFile warfile) {
		MsgBean mbean = SysFilter.getMsgBean(0,"上传成功");
		String fileName = warfile.getOriginalFilename();
		String extName = FileUtils.getExtName(fileName);
		fileName = fileName.replaceAll(extName, "");
		String newFileName = fileName 
				+ DateUtils.date2str(new Date(), "-yyyyMMdd-HHmmss")
				+ extName;
		String filePath = CommonUtils.getRealPath("/temp/" + newFileName);
		log.debug(filePath);
		File file = new File(filePath);
		try {
			warfile.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return Html(JSON.toJSONString(mbean));
	}
	
}
